package com.bootdo.wx.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.bootdo.wx.domain.Config;
import com.bootdo.wx.domain.Message;
import com.bootdo.wx.service.ConfigService;
import com.bootdo.wx.service.MessageService;
import com.front.web.wx.utils.SucaiUtils;
import com.front.web.wx.utils.TokenUtils;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.bootdo.common.config.BootdoConfig;
import com.bootdo.common.controller.BaseController;
import com.bootdo.common.domain.FileDO;
import com.bootdo.common.utils.FileType;
import com.bootdo.common.utils.FileUtil;
import com.bootdo.common.utils.PageUtils;
import com.bootdo.common.utils.Query;
import com.bootdo.common.utils.R;

/**
 * 
 * 
 * @author haojiangbo
 * @email 2100272728@qq.com
 * @date 2018-11-23 15:14:45
 */
 
@Controller
@RequestMapping("/wx/message")
public class MessageController extends BaseController{
	@Autowired
	private MessageService messageService;
	@Autowired
	private ConfigService configService;
	@Autowired
	private BootdoConfig bootdoConfig;
	@ModelAttribute
	public Message get(@RequestParam(required=false) Integer id) {
		if (id != null){
			return messageService.get(id);
		}else{
			return new Message();
		}
	}
	@PostMapping("/getById")
	@ResponseBody
	R getById(Message message) {
		return R.ok().put("i",message);
	}
	//insert into sys_menu(parent_id,name,url,perms,type)  values (3,'微信被动消息','/wx/message','wx:message:message',1)
	//insert into sys_menu(parent_id,name,url,perms,type)  values (155,'添加','/wx/message/add','wx:message:add',2)
	//insert into sys_menu(parent_id,name,url,perms,type)  values (155,'修改','','wx:message:edit',2)
	//insert into sys_menu(parent_id,name,url,perms,type)  values (155,'删除','/wx/message/remove','wx:message:remove',2)
	//insert into sys_menu(parent_id,name,url,perms,type)  values (155,'批量删除','/wx/message/batchRemove','wx:message:batchRemove',2)
	//type 0是分类菜单 1是小菜但 2是按钮
	@GetMapping()
	@RequiresPermissions("wx:message:message")	
	String Message(){
	    return "wx/message/message";
	}
	
	@ResponseBody
	@PostMapping("/list")
	@RequiresPermissions("wx:message:message")
	public PageUtils list(@RequestParam Map<String, Object> params){
		//查询列表数据
        Query query = new Query(params);
		List<Message> messageList = messageService.list(query);
		int total = messageService.count(query);
		PageUtils pageUtils = new PageUtils(messageList, total);
		return pageUtils;
	}
	
	@GetMapping("/add")
	@RequiresPermissions("wx:message:edit")
	String add(){
	    return "wx/message/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("wx:message:edit")
	String edit(@PathVariable("id") Integer id,Model model){
		Message message = messageService.get(id);
		model.addAttribute("message", message);
	    return "wx/message/edit";
	}
	
	/**
	 * 保存
	 * @throws IOException 
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("wx:message:edit")
	public R save(Message message) throws IOException{

		/*if(null != file && file.getBytes().length > 0) {
			String fileName = file.getOriginalFilename();
			fileName = FileUtil.renameToUUID(fileName);
			String picPath = "/files/" + fileName;
		
			try {
				FileUtil.uploadFile(file.getBytes(), bootdoConfig.getUploadPath(), fileName);
			} catch (Exception e) {
				return R.error();
			}
			
			File file2 = new File(bootdoConfig.getUploadPath()+fileName);	
			Config  config  =  configService.getByUserId(getUserId());
			String mediaIdTemp =  SucaiUtils.uploadPermanentMedia2(TokenUtils.getToken(config), file2, "test", "test");
			JSONObject json = (JSONObject) JSONObject.parse(mediaIdTemp);
			message.setPic(picPath);
			message.setRemark(json.getString("media_id"));
		}*/
		if(messageService.save(message) > 0) {
			return R.ok();
		}else {
			return R.error();
		}
	}


	/**
	 * 保存   /wx/message/upFile
 	 * @throws IOException
	 */
	@ResponseBody
	@PostMapping("/upFile")
	public R upFile(@RequestParam("picFile") MultipartFile file) throws IOException{

		if(null != file && file.getBytes().length > 0) {
			String fileName = file.getOriginalFilename();
			fileName = FileUtil.renameToUUID(fileName);
			String picPath = "/files/" + fileName;
			String mediaId = "";
			try {
				FileUtil.uploadFile(file.getBytes(), bootdoConfig.getUploadPath(), fileName);
				File file2 = new File(bootdoConfig.getUploadPath()+fileName);
				Config  config  =  configService.getByUserId(1l);
				String mediaIdTemp =  SucaiUtils.uploadPermanentMedia2(TokenUtils.getToken(config), file2, "test", "test");
				JSONObject json = (JSONObject) JSONObject.parse(mediaIdTemp);
				mediaId  = json.getString("media_id");
			} catch (Exception e) {
				e.printStackTrace();
				return R.error();
			}
			return R.ok().put("fileName", picPath).put("mediaId",mediaId);
		}
		return R.error();
	}


	/**
	 * 修改
	 * @throws IOException 
	 * @throws JSONException 
	 */
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("wx:message:edit")
	public R update( Message message) throws JSONException, IOException{
		
		/*if(null != file && file.getBytes().length > 0) {
			String fileName = file.getOriginalFilename();
			fileName = FileUtil.renameToUUID(fileName);
			String picPath = "/files/" + fileName;
		
			try {
				FileUtil.uploadFile(file.getBytes(), bootdoConfig.getUploadPath(), fileName);
			} catch (Exception e) {
				return R.error();
			}
			
			File file2 = new File(bootdoConfig.getUploadPath()+fileName);	
			Config  config  =  configService.getByUserId(getUserId());
			String mediaIdTemp =  SucaiUtils.uploadPermanentMedia2(TokenUtils.getToken(config), file2, "test", "test");
			JSONObject json = (JSONObject) JSONObject.parse(mediaIdTemp);
			message.setPic(picPath);
			message.setRemark(json.getString("media_id"));
		}*/
		
		messageService.update(message);
		return R.ok();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("wx:message:edit")
	public R remove( Integer id){
		if(messageService.remove(id)>0){
		return R.ok();
		}
		return R.error();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("wx:message:edit")
	public R remove(@RequestParam("ids[]") Integer[] ids){
		messageService.batchRemove(ids);
		return R.ok();
	}
	
}